<template>
  <div>
    <el-tree
      :data="permissionsList"
      :props="{ label: 'name' }"
      show-checkbox
      default-expand-all
      check-strictly
      node-key="id"
      ref="treeRef"
    />
    <div>
      <el-button @click="hCancel">取消</el-button>
      <el-button @click="doSubmit">确定</el-button>
    </div>
  </div>
</template>
<script>
import { arrayToTree } from "@/utils/index";
import { getPermissionList } from "@/api/permissions";
import { getPermissionById, assignPrem } from "@/api/settings";
export default {
  props: {
    curId: {
      type: String,
      required: true,
    },
  },
  data() {
    return {
      permissionsList: [],
    };
  },
  created() {
    this.loadPermissionList();
    this.loadPermissionById();
  },
  methods: {
    async loadPermissionById() {
      const res = await getPermissionById(this.curId);
      console.log(res);
      this.$refs.treeRef.setCheckedKeys(res.data.permIds);
    },
    async loadPermissionList() {
      const res = await getPermissionList();
      // 转成树
      this.permissionsList = arrayToTree(res.data, "0");
    },
    hCancel() {
      this.$emit("close");
    },
    async doSubmit() {
      try {
        const permIds = this.$refs.treeRef.getCheckedKeys();
        const res = await assignPrem({ id: this.curId, permIds });
        this.$message.success(res.message);
        this.$emit("assignSuccess");
      } catch (err) {
        this.$message.error(err.message);
      }
    },
  },
};
</script>